package br.com.adimoveis.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.JComponent;

import br.com.adimoveis.util.ui.TogglePanel;

public abstract class AbstractCompositeView implements ISimpleView{

	private TogglePanel togglePanel;
	
	private Map<JComponent, IView> views;
	
	private IView currentView;
	
	public AbstractCompositeView(){
		togglePanel = new TogglePanel();
		togglePanel.addActionListener(new SelectionListener());
		views = new HashMap<JComponent, IView>();
	}
	
	public abstract Icon getIcon();
	
	public abstract String getTitle();
	
	public JComponent getComponent(){
		return togglePanel;
	}
	
	public void setViews(List<IView> subViews){
		boolean selected = false;
		for(IView view : subViews){
			selected = subViews.indexOf(view) == 0;
			togglePanel.addPage(view.getTitle(), view.getIcon(), view.getComponent(), selected);
			views.put(view.getComponent(), view);
			if(selected){
				this.currentView = view;
			}
		}
	}
	
	public IView[] getSubViews(){
		return views.values().toArray(new IView[views.size()]);
	}
	
	public void turnListenersOn() {
		if(currentView != null){
			currentView.turnListenersOn();
		}
		
	}
	
	public void turnListenersOff() {
		for(IView view : views.values()){
			view.turnListenersOff();
		}
	}
	
	private class SelectionListener implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			JComponent currentComponent = (JComponent) e.getSource();
			
			if(currentView != null){
				currentView.turnListenersOff();
			}
			
			currentView = views.get(currentComponent);
			currentView.turnListenersOn();
		}
		
	}
}
